﻿/*
 * JsonSerializableObject
 * 
 * object that can be serialized into JSON
 * 
 * created by: asida@centrum.cz
 * 
 * initial implementation: 6.12.2011
 * last updated:
 */
using System.IO;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace uhul
{

  /// <summary>
  /// base class that server functions for JSON serialization
  /// </summary>
  /// <typeparam name="T"></typeparam>
  public abstract class JsonSerializableObject<T>
  {


    /// <summary>
    /// serializes instance into Json
    /// </summary>
    /// <returns>vraci <c>string</c> s Json reprezentaci objektu</returns>
    public string ToJson()
    {
      using (var memoryStream = new MemoryStream())
      {
        //var serializer = new DataContractSerializer(typeof(T));
        //serializer.WriteObject(memoryStream, this);

        var serializer = new DataContractJsonSerializer(typeof(T));
        serializer.WriteObject(memoryStream, this);

        memoryStream.Seek(0, SeekOrigin.Begin);

        var reader = new StreamReader(memoryStream);
        string content = reader.ReadToEnd();
        return content;
      }
    }





    /// <summary>
    /// static function, loads object from <c>string</c> data
    /// and converts to object such as command, jprl, ku, etc...
    /// </summary>
    /// <param name="data">input string with Json data</param>
    /// <returns>reference to instance of <c>T</c></returns>
    public static T Parse(string data)
    {
      using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(data)))
      {
        //var serializer = new DataContractSerializer(typeof(T));
        //T theObject = (T)serializer.ReadObject(stream);
        //return theObject;


        DataContractJsonSerializer s =
          new DataContractJsonSerializer(typeof(T));
        T theObject = (T)s.ReadObject(stream);
        return theObject;

      }
    }


  }
}
